package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.compose.ui.graphics.Color
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.CardMatchingGame

class Cardactivity : ComponentActivity() , View.OnClickListener{
    @SuppressLint("MissingInflatedId")
    private var highScore=0
    lateinit var game: CardMatchingGame
    val cardButtons= mutableListOf<Button>()
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_cardgame)
        val gridLayout=findViewById<GridLayout>(R.id.gridlayout)
        for (v in gridLayout.children){
            if(v is Button){
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        game=CardMatchingGame(cardButtons.count())
        updateUI()
        val reset=findViewById<Button>(R.id.reset)
        reset.setOnClickListener {
            game=CardMatchingGame(cardButtons.count())
            updateUI()
        }
        // 返回主界面按钮点击事件
        val btnReturn: Button = findViewById(R.id.back)
        btnReturn.setOnClickListener {
            highScore = calculateHighScore()
            val intent = Intent()
            intent.putExtra("highScore", highScore)
            setResult(RESULT_OK, intent)
            finish()
        }
    }
    @SuppressLint("ResourceAsColor")
    fun updateUI(){
        for(button in cardButtons){
            val index=cardButtons.indexOf(button)
            val card=game.cardAtIndex(index)
            button.isEnabled=!card.isMatched
            if(card.isChosen){
                button.text=card.toString()
                button.setBackgroundColor(R.color.white)
            }else{
                button.text=""
                button.setBackgroundResource(R.drawable.first)
            }
        }
        val score=findViewById<TextView>(R.id.score)
        score.text=String.format("%s%d","Score:",game.score)
    }

    override fun onClick(v:View?) {
        if (v is Button){
            val index=cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
    private fun calculateHighScore(): Int {
        // 计算最高分的逻辑
        return game.score// 示例分数
    }
}
